const webim = require('../../utils/webim_wx.js')
const msgType = require('./msgType.js')

const app = getApp()

// 从指定消息seq开始获取群历史消息
function getGroupHistoryMsgsFromSeq(groupId, msgSeq, length = 10) {
    return new Promise((resolve, reject) => {
        //拉取最新的群历史消息
        let options = {
            'GroupId': groupId,
            'ReqMsgSeq': msgSeq,
            'ReqMsgNumber': length
        }
        if (options.ReqMsgSeq == null || options.ReqMsgSeq == undefined || options.ReqMsgSeq <= 0) {
            resolve([])
            return;
        }
        webim.syncGroupMsgs(
            options,
            function(msgList) {
                resolve(msgList)
            },
            function(err) {
                reject(err)
            }
        );
    })
}

// 获取群最新历史消息
function getLatestGroupHistoryMsgs(groupId, length = 10) {

    var options = {
        'GroupIdList': [
            groupId
        ],
        'GroupBaseInfoFilter': [
            'NextMsgSeq'
        ],
    }
    return new Promise((resolve, reject) => {
        webim.getGroupInfo(
            options,
            resp => resolve(resp.GroupInfo[0].NextMsgSeq - 1),
            err => reject(err)
        )
    }).then(latestMsgSeq => getGroupHistoryMsgsFromSeq(groupId, latestMsgSeq, length))

}

function sendTextMessageToGroup(groupId, message) {
    return new Promise((resolve, reject) => {

        //获取消息长度
        var msgLen = webim.Tool.getStrBytes(msg);
        if (message.length < 1) {
            throw "发送的消息不能为空!"
            return;
        }
        if (msgLen > webim.MSG_MAX_LENGTH.GROUP) {
            throw "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)"
            return;
        }
        // if (!selSess) {
        var selSess = new webim.Session(webim.SESSION_TYPE.GROUP, groupId)
        // }
        var isSend = true; //是否为自己发送
        var seq = -1; //消息序列，-1表示 SDK 自动生成，用于去重
        var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
        var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
        var subType = webim.GROUP_MSG_SUB_TYPE.COMMON;

        var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, app.globalData.userInfo.identifier, subType, /*loginInfo.identifierNick*/ );
        var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
        //解析文本和表情
        var expr = /\[[^[\]]{1,3}\]/mg;
        var emotions = message.match(expr);
        if (!emotions || emotions.length < 1) {
            text_obj = new webim.Msg.Elem.Text(message);
            msg.addText(text_obj);
        } else {
            for (var i = 0; i < emotions.length; i++) {
                tmsg = message.substring(0, message.indexOf(emotions[i]));
                if (tmsg) {
                    text_obj = new webim.Msg.Elem.Text(tmsg);
                    msg.addText(text_obj);
                }
                emotionIndex = webim.EmotionDataIndexs[emotions[i]];
                emotion = webim.Emotions[emotionIndex];
                if (emotion) {
                    face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
                    msg.addFace(face_obj);
                } else {
                    text_obj = new webim.Msg.Elem.Text(emotions[i]);
                    msg.addText(text_obj);
                }
                restMsgIndex = message.indexOf(emotions[i]) + emotions[i].length;
                message = message.substring(restMsgIndex);
            }
            if (message) {
                text_obj = new webim.Msg.Elem.Text(message);
                msg.addText(text_obj);
            }
        }


        webim.sendMsg(msg, function(resp) {
            // 群聊时，长轮询接口会返回自己发的消息
            console.log(resp)
            resolve(resp)
        }, function(err) {
            reject(err)
        })

    })

}

function sendPictureMessageToGroup(groupId, imageUrl) {

    return new Promise((resolve, reject) => {


        let selSess = new webim.Session(webim.SESSION_TYPE.GROUP, groupId)

        var isSend = true; //是否为自己发送
        var seq = -1; //消息序列，-1表示 SDK 自动生成，用于去重
        var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
        var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
        var subType = webim.GROUP_MSG_SUB_TYPE.COMMON;

        var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, app.globalData.userInfo.identifier, subType, /*loginInfo.identifierNick*/ );
        var custom_obj = new webim.Msg.Elem.Custom(imageUrl, 'custom picture message', msgType.picture);
        msg.addCustom(custom_obj);

        //调用发送图片接口
        webim.sendMsg(msg, function(resp) {
            console.log(resp)
            resolve()

        }, function(err) {
            console.log(err)
            reject(err)
        })
    })

}


function sendVoiceMessageToGroup(groupId, voiceUrl) {

    return new Promise((resolve, reject) => {


        let selSess = new webim.Session(webim.SESSION_TYPE.GROUP, groupId)

        var isSend = true; //是否为自己发送
        var seq = -1; //消息序列，-1表示 SDK 自动生成，用于去重
        var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
        var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
        var subType = webim.GROUP_MSG_SUB_TYPE.COMMON;

        var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, app.globalData.userInfo.identifier, subType, /*loginInfo.identifierNick*/ );
        var custom_obj = new webim.Msg.Elem.Custom(voiceUrl, 'custom voice message', msgType.voice);
        msg.addCustom(custom_obj);

        webim.sendMsg(msg, function(resp) {
            console.log(resp)
            resolve()

        }, function(err) {
            console.log(err)
            reject(err)
        });


    })
}

function sendVideoMessageToGroup(groupId, videoUrl) {
    return new Promise((resolve, reject) => {


        let selSess = new webim.Session(webim.SESSION_TYPE.GROUP, groupId)

        var isSend = true; //是否为自己发送
        var seq = -1; //消息序列，-1表示 SDK 自动生成，用于去重
        var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
        var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
        var subType = webim.GROUP_MSG_SUB_TYPE.COMMON;

        var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, app.globalData.userInfo.identifier, subType, /*loginInfo.identifierNick*/ );
        var custom_obj = new webim.Msg.Elem.Custom(videoUrl, 'custom voice message', msgType.video);
        msg.addCustom(custom_obj);

        webim.sendMsg(msg, function(resp) {
            console.log(resp)
            resolve()
        }, function(err) {
            console.log(err)
            reject(err)
        });



    })
}

module.exports = {
    getLatestGroupHistoryMsgs,
    getGroupHistoryMsgsFromSeq,
    sendTextMessageToGroup,
    sendPictureMessageToGroup,
    sendVoiceMessageToGroup,
    sendVideoMessageToGroup,
}